import React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { IndexList } from "@taroify/core";
import { Text, View } from "@tarojs/components";
import { postGetallcities } from "@/apis/endpoint/home";
import { Region } from "@/apis/endpoint/model";
import GpContainer from "@/components/GpContainer";
import { GpSearchInput } from "@/components/GpSeachInput";
import { debounce } from "@/utils/helper";
import styles from "./index.module.css";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { useRouter } from "@tarojs/taro";
import { historyCity } from "@/utils/ls/history-city";
import { navigate } from "@/utils/navigation";
import { withCache } from "@/utils/cache";

type CityGroup = {
  [character: string]: Region[]
}

type SearchItem = {
  node: React.ReactNode
  item: Region
}

type RouteParams = {
  cityid?: string
}
export default function Index() {
  const router = useRouter<RouteParams>()
  const { eventChannel } = useNavigateEventChannel()
  const availableCities = useRef<Region[]>([])
  const [cityGroup, setCityGroup] = useState<CityGroup>({})
  const [hotCities, setHotCities] = useState<Region[]>([])
  const [currentCity, setCurrentCity] = useState<Region>()
  const customIndexList = useMemo(() => {
    const chars = Object.keys(cityGroup)
    chars.sort((a, b) => a.localeCompare(b))
    return chars
  }, [cityGroup])
  const [historyRecords] = useState(historyCity.get())
  const [search, setSearch] = useState("")
  const [searchList, setSearchList] = useState<SearchItem[]>([])
  const triggerSearch = useCallback(debounce(300, (value: string) => {
    const text = value.trim()
    if (text.length === 0) {
      setSearchList([])
      return;
    }
    const regEx = new RegExp(`(${text})`, "i");
    const nodes = availableCities.current
    .filter(item => regEx.test(item.name))
    .map(item => {
      const spliter = React.createElement(Text, {
        className: "text-theme"
      }, text)
      const parts = item.name.split(regEx).map<React.ReactNode>(part => {
        if (part === text) return spliter
        return part
      })
      return {
        node: parts,
        item
      }
    })
    setSearchList(nodes)
  }), [cityGroup])
  useEffect(() => {
    withCache("postGetallcities", () => postGetallcities().send())
    .then(data => {
      const _cityGroup: CityGroup = {}
      const _hotCities: Region[] = []
      data.forEach(item => {
        if (item.regionLevel === 2) {
          _cityGroup[item.firstCode.toUpperCase()] ??= []
          _cityGroup[item.firstCode.toUpperCase()].push(item)
          if (item.isHot) {
            _hotCities.push(item)
          }
          availableCities.current.push(item)
          if (router.params.cityid && item.id === router.params.cityid) {
            setCurrentCity(item)
          }
        }
      })
      setCityGroup(_cityGroup)
      setHotCities(_hotCities)
    })
  }, [])
  function handleSearchChange(value: string) {
    setSearch(value)
    triggerSearch(value)
  }
  function handleTapItem(item: Region) {
    process.env.NODE_ENV === "development" && console.log('点击了城市:', item)
    historyCity.push(item)
    if (eventChannel) {
      eventChannel.emit("chooseCity", item)
    }
    navigate()
  }
  function renderVisited() {
    return (
      <View className="mb-[64px]">
        <Text className="text-primary font-bold text-[32px]">当前/历史访问城市</Text>
        <View className="grid grid-cols-3 gap-[18px] box-border mt-[32px]">
          {/* {
            currentCity
            ? (
            <View onClick={() => handleTapItem(currentCity)} className="flex flex-row justify-center items-center box-border rounded-[16px] h-[80px] bg-[#F7F8FA] text-primary">
              <Text className="text-[28px]">{currentCity.name}</Text>
            </View>
            ) : null
          } */}
          {
            historyRecords.map(item => (
            <View key={item.id} onClick={() => handleTapItem(item)} className="flex flex-row justify-center items-center box-border rounded-[16px] h-[80px] bg-[#F7F8FA] text-primary">
              <Text className="text-[28px]">{item.name}</Text>
            </View>
            ))
          }
        </View>
      </View>
    )
  }
  function renderHots() {
    if (hotCities.length <= 0) return null
    return (
      <View className="mb-[64px]">
        <Text className="text-primary font-bold text-[32px]">热门城市</Text>
        <View className="grid grid-cols-3 gap-[18px] box-border mt-[32px]">
          {
            hotCities.map(item => (
              <View key={item.id} onClick={() => handleTapItem(item)} className="flex flex-row justify-center items-center box-border rounded-[16px] h-[80px] bg-[#F7F8FA] text-primary">
                <Text className="text-[28px]">{item.name}</Text>
              </View>
            ))
          }
        </View>
      </View>
    )
  }
  function renderIndexList() {
    return (
      <IndexList className={styles.indexList}>
        {customIndexList.map(char => {
          return (
            <Fragment key={char} >
              <IndexList.Anchor index={char}>
                <Text className="text-primary font-bold text-[32px]">{char}</Text>
              </IndexList.Anchor>
              <View className="grid grid-cols-3 gap-[18px] box-border mt-[32px] mb-[64px]">
                {
                  cityGroup[char].map(item => (
                  <View key={item.id} onClick={() => handleTapItem(item)} className="flex flex-row justify-center items-center box-border rounded-[16px] h-[80px] bg-[#F7F8FA] text-primary">
                    <Text className="text-[28px]">{item.name}</Text>
                  </View>
                  ))
                }
              </View>
            </Fragment>
          )
        })}
      </IndexList>
    )
  }
  function renderCityList() {
    return (
      <View className="pl-[32px] pr-[58px] pt-[36px] box-border">
        {renderVisited()}
        {renderHots()}
        {renderIndexList()}
      </View>
    )
  }
  function renderSearchList() {
    return (
      <View className="box-border px-[32px]">
        {
          searchList.map(item => (
            <View onClick={() => handleTapItem(item.item)} className="flex flex-row items-center h-[138px] text-primary text-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
              {item.node}
            </View>
          ))
        }
      </View>
    )
  }
  return (
    <GpContainer className="bg-white">
      <View className="px-[32px] pb-[24px] flex flex-col">
        <Text className="text-primary font-bold text-[48px] leading-[48px] pt-[20px]">选择工作城市</Text>
        <GpSearchInput
          className="mt-[32px]"
          placeholder="搜索城市名称"
          value={search}
          onChange={handleSearchChange}
        />
      </View>
      { searchList.length > 0 ? renderSearchList() : renderCityList() }
    </GpContainer>
  )
}
